package com.recharge.web.controller;


import com.recharge.common.domain.PageDO;
import com.recharge.common.enums.ErrorCode;
import com.recharge.common.result.ResultDO;
import com.recharge.common.result.web.ObjectResponse;
import com.recharge.common.util.FunctionUtil;
import com.recharge.domain.query.GoodsQueryDO;
import com.recharge.domain.vo.GoodsDO;
import com.recharge.domain.vo.RegionDO;
import com.recharge.service.GoodsService;
import com.recharge.service.RegionService;
import io.swagger.annotations.ApiOperation;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 商品表 前端控制器
 * </p>
 *
 * @author reagan
 * @since 2020-08-19
 */
@RestController
@RequestMapping("/goods")
public class GoodsController extends BaseController {

	@Autowired
    private GoodsService goodsService;
	@Autowired
	private RegionService regionService;

	@Value("${file.goods.template}")
	private String fileTemplatePath;

	@RequiresPermissions("goods:page")
	@RequestMapping(value="/page.html", method = RequestMethod.POST)
	@ApiOperation(value="分页查询商品", notes="")
	public @ResponseBody  ObjectResponse<PageDO> page(@RequestBody GoodsQueryDO query) {

	 	ObjectResponse<PageDO> response = new ObjectResponse<>();

	 	ResultDO result = goodsService.find(query);

	 	if(result.isSuccess()) {
			response.setData((PageDO) result.getModel(ResultDO.FIRST_MODEL_KEY));
		} else {
			response.setStatus(result.getErrorCode().getCode());
			response.setMsg(result.getErrorCode().getMsg());
		}

	 	return response;
	 }

	@RequiresPermissions("goods:download")
	@RequestMapping(value="/download.html", method = RequestMethod.POST)
	@ApiOperation(value="商品下载", notes="")
	public void download(@RequestBody GoodsQueryDO query, HttpServletResponse response) {
		ResultDO result = goodsService.findList(query);
		List<GoodsDO> list= (List<GoodsDO>) result.getModel(ResultDO.FIRST_MODEL_KEY);
		List<Object> downloadList = new ArrayList<>();
		try{
			if(list !=null ){
				list.stream().forEach( item -> {
					Map<String,Object> data = new HashMap<>();
					String a4 = "全国";
					if(item.getRegionType() == 1){
						a4 = "全国";
					}
					if(item.getRegionType() == 2){
						ResultDO regionResult = regionService.get(item.getProvinceCode());
						if(regionResult.isSuccess()){
							RegionDO region = (RegionDO) regionResult.getModel(ResultDO.FIRST_MODEL_KEY);
							a4 = region.getName();
						} else {
							a4 = item.getProvinceCode();
						}
					}
					if(item.getRegionType() == 3){
						ResultDO regionResult = regionService.get(item.getProvinceCode());
						if(regionResult.isSuccess()){
							RegionDO region = (RegionDO) regionResult.getModel(ResultDO.FIRST_MODEL_KEY);
							a4 = region.getName();
							regionResult = regionService.get(item.getCityCode());
							if(regionResult.isSuccess()){
								region = (RegionDO) regionResult.getModel(ResultDO.FIRST_MODEL_KEY);
								a4 += "/" + region.getName();
							} else {
								a4 += "/" + item.getCityCode();
							}
						} else {
							a4 = item.getProvinceCode();
						}
					}
					data.put("a1", item.getGoodsNo() );
					data.put("a2", item.getTitle() );
					data.put("a3", item.getDenomination());
					data.put("a4", a4 );
					data.put("a5", item.getServiceProvider());
					downloadList.add(data);
				});
			}
			Map map = new HashMap();
			map.put("data",downloadList);
			map.put("fun", new FunctionUtil());
			InputStream is = new FileInputStream(fileTemplatePath);
			// 实例化 XLSTransformer 对象
			XLSTransformer xlsTransformer = new XLSTransformer();
			// 获取 Workbook ，传入 模板 和 数据
			Workbook workbook =  xlsTransformer.transformXLS(is,map);
			// 设置文件名
			response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("商品列表.xls" ,"UTF-8"));
			// 写出文件
			OutputStream os = new BufferedOutputStream( response.getOutputStream() );
			// 输出
			workbook.write(os);
			// 关闭和刷新管道，不然可能会出现表格数据不齐，打不开之类的问题
			is.close();
			os.flush();
			os.close();
		}catch (Exception e){
			e.printStackTrace();
		}
	}


	@RequiresPermissions("goods:add")
	//@OperationLogDetail(detail = "添加商品", operationType = OperationLogType.ADD)
	@RequestMapping(value="/add.html", method = RequestMethod.POST)
	@ApiOperation(value="添加商品", notes="")
	public @ResponseBody  ObjectResponse<Object> add(@RequestBody GoodsDO param) {
	 	ObjectResponse<Object> response = new ObjectResponse<>();
	 	
	 	param.setCreator(getUserName());

	 	ResultDO result = goodsService.add(param);
	 	if(result.isSuccess()) {
			response.setData(null);
		} else {
			response.setStatus(result.getErrorCode().getCode());
			response.setMsg(result.getErrorCode().getMsg());
		}
	 	return response;
	 }

	@RequiresPermissions("goods:addBatch")
	@RequestMapping(value="/addBatch.html", method = RequestMethod.POST)
	@ApiOperation(value="批量同意运营商添加商品", notes="")
	public @ResponseBody  ObjectResponse<Object> addBatch(@RequestBody GoodsDO param) {
		ObjectResponse<Object> response = new ObjectResponse<>();

		ResultDO result = goodsService.addBatch(param.getParam(), getUserName());
		if(result.isSuccess()) {
			response.setData(null);
		} else {
			response.setStatus(result.getErrorCode().getCode());
			response.setMsg(result.getErrorCode().getMsg());
		}
		return response;
	}


	@RequiresPermissions("goods:delete")
//	@OperationLogDetail(detail = "删除商品", operationType = OperationLogType.DELETE)
	@RequestMapping(value="/delete.html", method = RequestMethod.POST)
	@ApiOperation(value="删除商品", notes="")
	public @ResponseBody  ObjectResponse<Object> delete(@RequestBody GoodsDO param) {
	 	ObjectResponse<Object> response = new ObjectResponse<>();
	 	
	 	ResultDO result = goodsService.remove(param.getId(), getUserName());
	 	if(result.isSuccess()) {
			response.setData(null);
		} else {
			response.setStatus(result.getErrorCode().getCode());
			response.setMsg(result.getErrorCode().getMsg());
		}
	 	return response;
	 }

	@RequiresPermissions("goods:deleteList")
//	@OperationLogDetail(detail = "批量删除商品", operationType = OperationLogType.DELETE)
	@RequestMapping(value="/deleteList.html", method = RequestMethod.POST)
	@ApiOperation(value="批量删除商品", notes="")
	public @ResponseBody  ObjectResponse<Object> deleteList(@RequestBody GoodsDO param) {
		ObjectResponse<Object> response = new ObjectResponse<>();

		ResultDO result = goodsService.removeList(param.getGoodsIds().split(","), getUserName());
		if(result.isSuccess()) {
			response.setData(null);
		} else {
			response.setStatus(result.getErrorCode().getCode());
			response.setMsg(result.getErrorCode().getMsg());
		}
		return response;
	}


	@RequiresPermissions("goods:update")
//	@OperationLogDetail(detail = "修改商品", operationType = OperationLogType.UPDATE)
	@RequestMapping(value="/update.html", method = RequestMethod.POST)
	@ApiOperation(value="修改商品", notes="")
	public @ResponseBody  ObjectResponse<Object> update(@RequestBody GoodsDO param) {
	 	ObjectResponse<Object> response = new ObjectResponse<>();
	 	
	 	param.setModifier(getUserName());
	 	
	 	ResultDO result = goodsService.edit(param);
	 	if(result.isSuccess()) {
			response.setData(null);
		} else {
			response.setStatus(result.getErrorCode().getCode());
			response.setMsg(result.getErrorCode().getMsg());
		}
	 	return response;
	 }

	@RequiresPermissions("goods:get")
	@RequestMapping(value="/get.html", method = RequestMethod.POST)
	@ApiOperation(value="查询商品详情", notes="")
	public @ResponseBody  ObjectResponse<Object> get(@RequestBody GoodsDO param) {
	 	ObjectResponse<Object> response = new ObjectResponse<>();
	 	ResultDO result = goodsService.get(param.getId());
	 	if(result.isSuccess()) {
			response.setData(result.getModel(ResultDO.FIRST_MODEL_KEY));
			System.out.println(result.getModel(ResultDO.SECOND_MODEL_KEY));
		} else {
			response.setStatus(result.getErrorCode().getCode());
			response.setMsg(result.getErrorCode().getMsg());
		}
	 	return response;
	 }


	@RequiresPermissions("goods:updateStatus")
//	@OperationLogDetail(detail = "修改商品上下架", operationType = OperationLogType.UPDATE)
	@RequestMapping(value="/updateStatus.html", method = RequestMethod.POST)
	@ApiOperation(value="修改商品上下架", notes="")
	public @ResponseBody  ObjectResponse<Object> updateStatus(@RequestBody GoodsDO param) {
	 	ObjectResponse<Object> response = new ObjectResponse<>();
	 	
	 	ResultDO result = goodsService.updateStatus(param.getId(), param.getStatus(), getUserName());
	 	if(result.isSuccess()) {
			response.setData(null);
		} else {
			response.setStatus(result.getErrorCode().getCode());
			response.setMsg(result.getErrorCode().getMsg());
		}
	 	return response;
	 }

	@RequiresPermissions("goods:saveRelation")
//	@OperationLogDetail(detail = "商品与商品组关联", operationType = OperationLogType.UPDATE)
	@RequestMapping(value="/saveRelation.html", method = RequestMethod.POST)
	@ApiOperation(value="商品与商品组关联", notes="")
	public @ResponseBody  ObjectResponse<Object> saveRelation(@RequestBody GoodsDO param) {
	 	ObjectResponse<Object> response = new ObjectResponse<>();
	 	
	 	if(StringUtils.isEmpty(param.getGoodsIds())) {
	 		response.setStatus(ErrorCode.PARAM_GET_ERROR.getCode());
			response.setMsg(ErrorCode.PARAM_GET_ERROR.getMsg());
	 	} else {
	 		ResultDO result = goodsService.saveRelation(param.getGroupId(), param.getGoodsIds().split(","),  getUserName());
		 	if(result.isSuccess()) {
				response.setData(null);
			} else {
				response.setStatus(result.getErrorCode().getCode());
				response.setMsg(result.getErrorCode().getMsg());
			}
	 	}
	 	return response;
	 }


	@RequiresPermissions("goods:saveShelfBatch")
//	@OperationLogDetail(detail = "批量商品上下架", operationType = OperationLogType.UPDATE)
	@RequestMapping(value="/saveShelfBatch.html", method = RequestMethod.POST)
	@ApiOperation(value="批量商品上下架：1，上级；0，下架", notes="")
	public @ResponseBody  ObjectResponse<Object> saveShelfBatch(@RequestBody GoodsDO param) {
		ObjectResponse<Object> response = new ObjectResponse<>();
		if(StringUtils.isEmpty(param.getGoodsIds()) ) {
	 		response.setStatus(ErrorCode.PARAM_GET_ERROR.getCode());
			response.setMsg(ErrorCode.PARAM_GET_ERROR.getMsg());
	 	} else {
		 	ResultDO result = goodsService.saveShelfBatch(param.getStatus(), param.getGoodsIds().split(","), getUserName());
		 	if(result.isSuccess()) {
				response.setData(null);
			} else {
				response.setStatus(result.getErrorCode().getCode());
				response.setMsg(result.getErrorCode().getMsg());
			}
	 	}
	 	return response;
	}
	
	
}
